import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import vitePluginTemplate from './src/plugin/vite-plugin-template'
// import eslintPlugin from 'vite-plugin-eslint'
import { resolve } from 'path'
import autoprefixer from 'autoprefixer'
import tailwindcss from 'tailwindcss'
import autoImport from 'unplugin-auto-import/vite'

import prtrp from 'postcss-rem-to-responsive-pixel'
import { UnifiedViteWeappTailwindcssPlugin as uvwt } from 'weapp-tailwindcss-webpack-plugin/vite'

const isH5 = process.env.UNI_PLATFORM === 'h5'

const postcssPlugins = [autoprefixer(), tailwindcss()]

const vitePlugins = [
  uni(),
  vitePluginTemplate(),
  autoImport({
    include: [
      /\.vue$/, /\.vue\?vue/,
    ],
    imports: [
      'vue',
      'uni-app',
      'pinia',
    ],
    eslintrc: {
      enabled: false,
      filepath: './.eslintrc-auto-import.json',
      globalsPropValue: true,
    },
    dts: true,
  }),
  // 增加下面的配置项,这样在运行时就能检查eslint规范
  // eslintPlugin({
  //   include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue']
  // })
] as any[]

if (!isH5) {
  vitePlugins.push(uvwt())
  postcssPlugins.push(
    prtrp({
      rootValue: 32,
      propList: ['*'],
      transformUnit: 'rpx',
    }),
  )
}

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 3002, //前端服务启动的端口号
    hmr: true, //添加热更新
    https: false,
    host: 'localhost',
    open: true, // 项目启动后自动打开页面
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
  optimizeDeps: {
    exclude: ['vue-demi'],
  },
  resolve: {
    // 配置解析别名
    alias: {
      '@': resolve(__dirname, 'src'),
      '@/stores': resolve(__dirname, 'src/stores'),
      '@/components': resolve(__dirname, 'src/components'),
      '@/utils': resolve(__dirname, 'src/utils'),
    },
  },
  base: './',
  plugins: vitePlugins,
  css: {
    postcss: {
      plugins: postcssPlugins,
    },
  },
  define: {
    'process.env': process.env, // vite 中 process.env已经被遗弃了需要加此配置项
  },
})
